package com.heatup.apt.common.util.Netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;

import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.SSLEngine;

/**
 * Created by blank on 2017/11/17 上午9:57
 */
public class SsslChannelInitializer extends ChannelInitializer<Channel> {

    private final SslContext context;
    private final boolean startTls;

    public SsslChannelInitializer(SslContext context, boolean startTls) { //使用构造函数来传递 SSLContext 用于使用(startTls 是否启用)
        this.context = context;
        this.startTls = startTls;
    }


    @Override
    protected void initChannel(Channel ch) throws Exception {
        SSLEngine engine = context.newEngine(ch.alloc()); //从 SslContext 获得一个新的 SslEngine 。给每个 SslHandler 实例使用一个新的 SslEngine
        engine.setUseClientMode(true); //设置 SslEngine 是 client 或者是 server 模式
        ch.pipeline().addFirst("ssl", new SslHandler(engine, startTls));
    }
}
